package cn.yujiago.miaosha.service.impl;

import cn.yujiago.miaosha.dto.GoodsDTO;
import cn.yujiago.miaosha.dto.Result;
import cn.yujiago.miaosha.entity.MiaoshaOrder;
import cn.yujiago.miaosha.entity.Order;
import cn.yujiago.miaosha.entity.User;
import cn.yujiago.miaosha.redis.MiaoshaKey;
import cn.yujiago.miaosha.redis.RedisService;
import cn.yujiago.miaosha.service.GoodsService;
import cn.yujiago.miaosha.service.MiaoshaService;
import cn.yujiago.miaosha.service.OrderService;
import cn.yujiago.miaosha.util.ImageCodeUtil;
import cn.yujiago.miaosha.util.MyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.util.List;

@Service
public class MiaoshaServiceImpl implements MiaoshaService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;

    @Override
    public Result<List<GoodsDTO>> getMiaoshaList() {

        List<GoodsDTO> list = goodsService.getMiaoshaList();

        return Result.success(list);
    }

    @Override
    public BufferedImage createVerifyCode(User user, Long goodsId) {

        // 获取算数表达式
        String verifyCode = ImageCodeUtil.generateVerifyCode();

        // 获取结果
        int rnd = ImageCodeUtil.calc(verifyCode);

        // 将结果存到redis缓存
        redisService.set(MiaoshaKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, rnd);

        // 获取图片
        return ImageCodeUtil.createVerifyCodeImage(verifyCode);

    }

    @Override
    public boolean checkVerifyCode(User user, Long goodsId, String verifyCode) {
        String codeOld = redisService.get(MiaoshaKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, String.class);
        if(codeOld == null || !codeOld.equals(verifyCode) ) {
            return false;
        }
        // 匹配成功后，删除验证码
        redisService.delete(MiaoshaKey.getMiaoshaVerifyCode, user.getId()+","+goodsId);
        return true;
    }

    @Override
    public boolean checkPath(Long userId, Long goodsId, String path) {
        String pathOld = redisService.get(MiaoshaKey.getMiaoshaPath, ""+ userId + "_"+ goodsId, String.class);
        return path.equals(pathOld);
    }

    @Override
    public String createMiaoshaPath(Long userId, Long goodsId) {
        String str = MyStringUtil.md5(MyStringUtil.uuid());
        redisService.set(MiaoshaKey.getMiaoshaPath, ""+ userId + "_"+ goodsId, str);
        return str;
    }

    @Transactional
    @Override
    public Order miaosha(Long userId, GoodsDTO goods) {
        // 减库存
        boolean success = goodsService.reduceStock(goods);

        if(success) {
            //生成订单，order maiosha_order，并将其写入缓存
            return orderService.createOrder(userId, goods);
        }else {
            setGoodsOver(goods.getId());
            return null;
        }
    }

    @Override
    public Long getMiaoshaResult(Long userId, Long goodsId) {
        // 从缓存中查询是否存在订单
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(order != null) {// 秒杀成功
            return order.getOrderId();
        }else {
            boolean isOver = getGoodsOver(goodsId);
            if(isOver) {
                return -1L;
            }else {
                return 0L;
            }
        }
    }

    private void setGoodsOver(Long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver, ""+goodsId, true);
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver, ""+goodsId);
    }
}
